<template>
<div class="user">
  <!-- 面包屑 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 卡片视图-->
  <el-card class="box-card">

    <!-- 搜索和操作用户区域 -->
    <div style="margin-top: 15px;">
      <el-row :gutter="24">
        <el-col :span="9">
          <el-input placeholder="请输入内容" clearable @clear="getUserList" class="input-with-select" v-model="queryData.query">
            <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户 -->
        <el-col :span="3">
         <el-button type="primary" @click="addUserDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>

   <!-- 用户列表页 -->
  <el-table
    border
    stripe
    :data="userList"
    style="width: 100%">
    <el-table-column type="index" label="#" width="50px"></el-table-column>
    <el-table-column prop="username" label="姓名"></el-table-column>
    <el-table-column prop="email" label="邮箱"></el-table-column>
    <el-table-column prop="mobile" label="电话"></el-table-column>
    <el-table-column prop="role_name" label="角色"></el-table-column>
    <el-table-column label="状态">
      <template slot-scope="scope">
        <!-- 查看文档，通过插槽的方式暴露数据 -->
        <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)">
        </el-switch>
      </template>
    </el-table-column>
    <!-- 编辑 -->
    <el-table-column width="200px" label="操作">
      <template slot-scope="scope">
         <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row.id)"></el-button>
         <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope.row.id)"></el-button>
         <el-tooltip :enterable="false" class="item" effect="dark" content="分配角色" placement="top">
         <el-button size="mini" type="warning" icon="el-icon-setting" @click="setRole(scope.row)"></el-button>
         </el-tooltip>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页区域 -->
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="queryData.pagenum"
    :page-sizes="[2, 4, 6, 8]"
    :page-size="queryData.pagesize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total">
  </el-pagination>

    </div>
  </el-card>
<!-- 添加用户对话框 -->
<el-dialog title="添加用户"
  :visible.sync="addUserDialogVisible"
  width="50%">
  <!-- 表单内容 -->
  <el-form :model="addUserForm" :rules="addRule" ref="addUserForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="addUserForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="addUserForm.password"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="addUserForm.email"></el-input>
    </el-form-item>
    <el-form-item label="手机" prop="mobile">
      <el-input v-model="addUserForm.mobile"></el-input>
    </el-form-item>
  </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="resetAddForm">重 置</el-button>
      <el-button type="primary" @click="addUser">确 定</el-button>
    </span>
</el-dialog>

<!-- 编辑用户对话框 -->
<el-dialog title="编辑用户"
  :visible.sync="editUserDialogVisible" width="50%">
  <!-- 表单内容 -->
  <el-form label-width="100px"
  class="demo-ruleForm"
  :rules="editRules"
  ref="editUserInfo"
  :model="editUserInfo"
  @close="resetEditForm"
  >
    <el-form-item label="用户名" prop="username">
      <el-input v-model="editUserInfo.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="editUserInfo.password"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="editUserInfo.email"></el-input>
    </el-form-item>
    <el-form-item label="手机" prop="mobile">
      <el-input v-model="editUserInfo.mobile"></el-input>
    </el-form-item>
  </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="editUserDialogVisible = false">重 置</el-button>
      <el-button type="primary" @click="editFormUser">确 定</el-button>
    </span>
</el-dialog>

<!-- 角色分配 -->
<el-dialog title="角色分配" :visible.sync="setRoleVisible" width="50%">
   <p>当前的用户:{{ userInfo.username}}</p>
   <p>当前的角色：{{userInfo.role_name}}</p>
   <div>
     分配新角色:
     <el-select v-model="rolesValue" placeholder="请选择">
     <el-option
       v-for="item in rolesList"
       :key="item.id"
       :label="item.roleName"
       :value="item.id">
     </el-option>
   </el-select>
   </div>
  <div slot="footer" class="dialog-footer">
    <el-button @click="setRoleVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRoles">确 定</el-button>
  </div>
</el-dialog>
</div>
</template>

<script>
export default {
  data () {
    // 验证邮箱的校验规则
    const checkEmail = (r, v, cb) => {
      var reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (reg.test(v)) {
        return cb()
      }
      cb(new Error('邮箱格式错误'))
    }
    // 验证手机号的规则
    const checkMobile = (r, v, cb) => {
      var reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(v)) {
        return cb()
      }
      cb(new Error('手机号码格式错误'))
    }
    return {
      name: 'user',
      queryData: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 添加按钮
      addUserDialogVisible: false,
      addUserForm: {
        username: 'xxx111',
        email: '14578@qq.com',
        password: '123455',
        mobile: '18786945698'
      },
      // 用户校验规则定义
      addRule: {
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改用户页面的数据
      editUserDialogVisible: false,
      // 修改前数据
      editUserInfo: {},
      // 修改用户校验规则
      editRules: {
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 角色权限分配
      setRoleVisible: false,
      // 当前表格数据
      userInfo: '',
      // 所有角色列表
      rolesList: [],
      // 选中的数据
      rolesValue: ''

    }
  },

  created () {
    this.getUserList()
  },

  methods: {
    // 获取用户列表数据
    async getUserList () {
      const { data: res } = await this.$axios.get('users', {
        params: this.queryData
      })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.total = res.data.total
      this.userList = res.data.users
    // console.log(res)
    },
    // 每页条数发生变化
    handleSizeChange (val) {
    // console.log(val)
      this.queryData.pagesize = val
      this.getUserList()
    },
    // 页码发生变化
    handleCurrentChange (val) {
      this.queryData.pagenum = val
      this.getUserList()
    },
    // 修改用户状态
    async userStateChange (userinfo) {
      // console.log(userinfo)
      const res = await this.$axios.put(`userinfo/${userinfo.id}${userinfo.mg_state}`)
      if (res.status !== 200) {
        // users.msg_state = !users.msg_state
        return this.$message.error('修改状态失败')
      }
      this.$message.success('修改状态成功')
    },
    // 重置添加表单
    resetAddForm () {
      this.$refs.addUserForm.resetFields()
    },
    // 添加用户
    addUser () {
      this.$refs.addUserForm.validate(async flag => {
        // console.log(flag)
        if (!flag) return
        // console.log('请求合法')
        // 发送请求
        const { data: res } = await this.$axios.post('users', this.addUserForm)
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addUserDialogVisible = false
        this.getUserList()
      })
    },
    // 修改用户信息
    async editUser (id) {
      this.editUserDialogVisible = true
      const { data: res } = await this.$axios.get('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.editUserInfo = res.data
    },
    // 重置编辑表单
    resetEditForm () {
      this.$refs.editUserInfo.resetFields()
    },
    // 编辑用户
    editFormUser () {
      this.$refs.editUserInfo.validate(async flag => {
        // console.log(flag)
        if (!flag) return
        const { data: res } = await this.$axios.put('users/' + this.editUserInfo.id, {
          email: this.editUserInfo.email,
          mobile: this.editUserInfo.mobile
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editUserDialogVisible = false
        this.getUserList()
      })
    },
    // 删除用户
    removeUser (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 点击了确认
          // console.log('确认删除')
          const { data: res } = await this.$axios.delete('users/' + id)
          if (res.meta.status !== 200) return this.$message.error('删除用户失败')
          this.$message.success('删除成功')
          this.getUserList()
        })
        .catch(() => {
          // 点击了取消
          this.$message.info('已取消删除')
        })
    },
    // 角色分配
    async setRole (userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$axios.get('/roles')
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取角色数据失败')
      this.rolesList = res.data
      this.setRoleVisible = true
    },
    // 点击分配角色
    async setRoles () {
      if (!this.rolesValue) return this.$message.error('小傻瓜，请选择角色名')
      const { data: res } = await this.$axios.put(`user/${this.userInfo.id}/role`, {
        rid: this.rolesValue
      })
      // console.log(res)
      if (res.meta.status !== 200) this.$message.error('修改失败')
      this.setRoleVisible = false
      this.getUserList()
    }

  }

}
</script>

<style scoped lang='less'>

</style>
